package BackTracking;

/**
 * Lettcode 79: https://leetcode-cn.com/problems/word-search/
 */
public class exist {
    private int m, n;

    private String word;

    private int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0) return false;
        m = board.length;
        n = board[0].length;
        this.word = word;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (backTracking(0, board, visited, i, j)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean backTracking(int curLen, char[][] board, boolean[][] visited, int r, int c) {
        if (curLen == word.length()) {
            return true;
        }
        if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c] || board[r][c] != word.charAt(curLen)) {
            return false;
        }
        visited[r][c] = true;
        for (int[] d: directions) {
            if (backTracking(curLen + 1, board, visited, r + d[0], c + d[1])) {
                return true;
            }
        }
        visited[r][c] = false;
        return false;
    }
}
